import { NextRequest, NextResponse } from 'next/server'
import { PrismaClient } from '@prisma/client'
import { compare } from 'bcryptjs'
import { sign } from 'jsonwebtoken'
import { cookies } from 'next/headers'

// 创建一个全局的 Prisma 实例
declare global {
  var prisma: PrismaClient | undefined
}

const prisma = global.prisma || new PrismaClient({
  log: ['query', 'info', 'warn', 'error'],
})

if (process.env.NODE_ENV !== 'production') {
  global.prisma = prisma
}

// JWT密钥，实际应该从环境变量获取
const JWT_SECRET = process.env.JWT_SECRET || 'your-secret-key';

// 统一的错误响应处理
const errorResponse = (message: string, error: any = null, status: number = 400) => {
  console.error(`API Error: ${message}`, error);
  return new NextResponse(
    JSON.stringify({ 
      success: false, 
      error: message,
      details: process.env.NODE_ENV === 'development' ? error?.message : undefined 
    }),
    { 
      status,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store, no-cache, must-revalidate',
        'Pragma': 'no-cache',
      }
    }
  );
};

// 统一的成功响应处理
const successResponse = (data: any) => {
  return new NextResponse(
    JSON.stringify({ success: true, data }),
    { 
      status: 200,
      headers: {
        'Content-Type': 'application/json',
        'Cache-Control': 'no-store, no-cache, must-revalidate',
        'Pragma': 'no-cache',
      }
    }
  );
};

export async function POST(request: NextRequest) {
  try {
    console.log('开始处理登录请求...');
    
    // 确保请求体是合法的 JSON
    let body;
    try {
      body = await request.json();
      console.log('请求体:', { ...body, password: '[REDACTED]' });
    } catch (e) {
      return errorResponse('无效的请求数据格式', e);
    }

    const { username, password, rememberMe = false } = body;

    // 参数验证
    if (!username || typeof username !== 'string') {
      return errorResponse('用户名不能为空');
    }

    if (!password || typeof password !== 'string') {
      return errorResponse('密码不能为空');
    }

    console.log('开始查询用户:', username);
    
    // 查找用户
    let user;
    try {
      user = await prisma.user.findFirst({
        where: {
          OR: [
            { username },
            { email: username }
          ]
        }
      });
      console.log('查询用户结果:', user ? { ...user, password: '[REDACTED]' } : '未找到用户');
    } catch (error) {
      return errorResponse('数据库查询错误', error, 500);
    }

    // 用户不存在
    if (!user) {
      return errorResponse('用户名或密码错误', null, 401);
    }

    console.log('开始验证密码...');
    
    // 验证密码
    let isValid;
    try {
      isValid = await compare(password, user.password);
      console.log('密码验证结果:', isValid);
    } catch (error) {
      return errorResponse('密码验证错误', error, 500);
    }

    if (!isValid) {
      return errorResponse('用户名或密码错误', null, 401);
    }

    // 检查用户状态
    if (!user.isActive) {
      return errorResponse('账号已被禁用，请联系管理员', null, 403);
    }

    console.log('生成 JWT token...');
    
    // 生成 JWT token
    let token;
    try {
      token = sign(
        {
          userId: user.id,
          username: user.username,
          email: user.email
        },
        JWT_SECRET,
        {
          expiresIn: rememberMe ? '7d' : '24h'
        }
      );
      console.log('Token 生成成功');
    } catch (error) {
      return errorResponse('令牌生成失败', error, 500);
    }

    console.log('创建会话记录...');
    
    try {
      // 创建新的会话
      await prisma.session.create({
        data: {
          userId: user.id,
          token,
          expires: new Date(Date.now() + (rememberMe ? 7 * 24 * 60 * 60 * 1000 : 24 * 60 * 60 * 1000)),
          userAgent: request.headers.get('user-agent') || '',
          ipAddress: request.headers.get('x-forwarded-for') || request.ip || '',
          rememberMe
        }
      });
      console.log('会话记录创建成功');

      // 更新用户的登录信息
      await prisma.user.update({
        where: { id: user.id },
        data: {
          lastLoginAt: new Date(),
          lastLoginIp: request.headers.get('x-forwarded-for') || request.ip || '',
          loginCount: { increment: 1 }
        }
      });
      console.log('用户登录信息更新成功');
    } catch (error) {
      console.error('Session/User update error:', error);
      // 继续处理，不要因为会话创建失败而阻止用户登录
    }

    console.log('准备返回成功响应...');

    // 创建响应
    const response = NextResponse.json({
      success: true,
      data: {
        token,
        user: {
          id: user.id,
          username: user.username,
          email: user.email,
          name: user.name,
          avatar: user.avatar
        }
      }
    });

    // 设置 cookie
    response.cookies.set({
      name: 'token',
      value: token,
      httpOnly: true,
      secure: process.env.NODE_ENV === 'production',
      sameSite: 'lax',
      maxAge: rememberMe ? 7 * 24 * 60 * 60 : 24 * 60 * 60, // 7天或1天
      path: '/',
    });

    console.log('登录成功，返回响应');
    return response;

  } catch (error) {
    // 捕获所有未处理的错误
    return errorResponse('服务器内部错误', error, 500);
  }
}
